﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Tower : MonoBehaviour
{
	#region 公开字段
	[Header("防御塔类型")]
	public TowerType towerType;

	[Header("塔的等级")]
	public int grade;

	[Header("塔的攻击力")]
	public float power;

	[Header("塔的攻击范围")]
	public float range;

	[Header("塔的攻击速度")]
	public float speed;

	[Header("攻击范围的显示")]
	public LineRenderer line;

	[Header("当前攻击目标")]
	public Transform attackTarget;

	[Header("防御塔朝向目标的旋转速度")]
	public float rotateSpeed;

	[Header("子弹参考物")]
	public Bullet bulletPrefab;
	#endregion

	private bool isShot;    // 子弹是否射击
	public bool IsShot { get => isShot; }

	/// <summary>
	/// 显示攻击范围
	/// </summary>
	public void ShowAttackRange() {
		// UIController.GetSingleton().ShowInfo(grade, power, range, attackSpeed);

		line.startWidth = 0.1f;
		line.endWidth = 0.1f;
		// float range = 5;

		Vector3[] points = new Vector3[61];
		float angle0 = Mathf.PI * 2 / (points.Length - 1);
		for (int i = 0; i < points.Length; i++) {
			points[i].x = range * Mathf.Cos(i * angle0) + transform.position.x;
			points[i].z = range * Mathf.Sin(i * angle0) + transform.position.z;
			points[i].y = 0.2f + transform.position.y;
		}

		line.positionCount = points.Length;
		line.SetPositions(points);
	}

	/// <summary>
	/// 塔射击, 间隔时间发射
	/// </summary>
	/// <param name="time"></param>
	/// <returns></returns>
	public IEnumerator Shot(float time) {

		while (isShot) {
			// 创建子弹
			Bullet bullet = Instantiate(bulletPrefab, bulletPrefab.transform.parent);
			bullet.transform.parent = null;
			bullet.StartMove(attackTarget, power); // 子弹移动
			yield return new WaitForSeconds(time);
		}
	}
	Coroutine co;


	private void Start() {
		ShowAttackRange();
	}


	public virtual void FindAttackTarget() {
		Enemy[] enemies = EnemyController.Singleton.GetEnemyInRange(
					new Vector3(transform.position.x, 0, transform.position.z),
					range
				);

		if (enemies.Length > 0) {

			attackTarget = enemies[0].transform;
		} else {
			attackTarget = null;
		}
	}

	private void Update() {
		if (GameController.Singleton.JudgeGameOver()) return;

		FindAttackTarget();

		if (attackTarget) {
			Vector3 target = new Vector3(attackTarget.position.x, transform.position.y, attackTarget.position.z);
			Quaternion quat = Quaternion.LookRotation(target - transform.position, Vector3.up);

			transform.rotation = Quaternion.Slerp(transform.rotation, quat, Time.deltaTime * rotateSpeed);

			if (!isShot) {
				// Debug.Log(11);
				isShot = true;
				co = StartCoroutine(Shot(1.5f / speed));
			}
		} else {
			if (co != null) StopCoroutine(co);
			co = null;
			isShot = false;
		}
	}
}
